<?php

/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/7/27
 * Time: 上午6:43
 */

namespace App\Services;

use App\Models\Contract;
use App\Models\ContractTemplate;

class ContractService extends Service
{

    public static function getContractList($limit, $offset, $order = 'desc', $option = [])
    {
        $query = Contract::where('status', 1);
        if (count($option) && count($option['query'])) {
            foreach ($option['query'] as $search) {
                $query = $query->where($search['key'], $search['operator'], $search['value']);
            }
        }
        $total = $query->count();
        $contracts = $query->orderBy('id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($contracts as $contract) {
            $data[] = [
                'id' => $contract->id,
                'sn' => $contract->sn,
                'user_id' => $contract->user_id,
                'realname' => $contract->realname,
                'apart_id' => $contract->apart_id,
                'apart_name' => $contract->apart_name,
                'start_end_time' => local_date($contract->start_at).' ~ '.local_date($contract->end_at),
                'order_at' => $contract->order_at,
                'process' => $contract->process,
                'status' => $contract->status,
                'is_renewable' => $contract->is_renewable
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function getUserContracts()
    {
        $contracts = Contract::where('status', 1)->where('process', 4)->where('end_at', '>', date('Y-m-d H:i:s', time()))->get();
        $data = [];
        foreach ($contracts as $contract) {
            $data[] = [
                'id' => $contract->id,
                'sn' => $contract->sn,
                'user_id' => $contract->user_id,
                'realname' => $contract->realname,
                'apart_id' => $contract->apart_id,
                'apart_name' => $contract->apart_name,
                'start_end_time' => local_date($contract->start_at).' ~ '.local_date($contract->end_at),
                'order_at' => $contract->order_at,
                'pay_order' => $contract->pay_order,
                'rent' => $contract->rent,
                'process' => $contract->process,
                'is_renewable' => $contract->is_renewable
            ];
        }

        return [
            'rows' => $data
        ];
    }

    public static function getContractDetail($id)
    {
        $contract = Contract::where('id', $id)->first();

        if (!$contract) {
            return [];
        }

        return [
            'data' => [
                'id' => $contract->id,
                'sn' => $contract->sn,
                'template_id' => $contract->template_id,
                'apart_id' => $contract->apart_id,
                'apart_name' => $contract->apart_name,
                'user_id' => $contract->user_id,
                'realname' => $contract->realname,
                'rent' => $contract->rent,
                'start_at' => $contract->start_at,
                'pay_order' => $contract->pay_order,
                'end_at' => $contract->end_at,
                'order_at' => $contract->order_at,
                'deposit' => $contract->deposit,
                'process' => $contract->process,
                'is_renewable' => $contract->is_renewable,
                'attachment' => $contract->attachment,
                'remark' => $contract->remark
            ]
        ];
    }

    public static function saveContract($data)
    {
        $contract = new Contract();
        if (array_key_exists('id', $data) && $data['id']) {
            $contract = Contract::where('id', $data['id'])->first();
            foreach ($data as $key => $value) {
                $contract->$key = $value;
            }
        } else {
            $contract->created_at = date('Y-m-d H:i:s', time());
        }

        $contract->updated_at = date('Y-m-d H:i:s', time());
        $contract->save();
    }

    public static function deleteContract($id)
    {
        $contract = Contract::where('id', $id)->first();
        $contract->status = 0;
        $contract->updated_at = date('Y-m-d H:i:s', time());
        $contract->save();
    }

    public static function getTemplateList($limit, $offset, $order = 'desc')
    {
        $query = ContractTemplate::where('status', 1);
        $total = $query->count();
        $templates = $query->orderBy('id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($templates as $template) {
            $data[] = [
                'id' => $template->id,
                'name' => $template->name,
                'created_at' => local_date($template->created_at, 'Y-m-d H:i:s')
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function getTemplates()
    {
        $templates = ContractTemplate::where('status', 1)->get();
        $data = [];
        foreach ($templates as $template) {
            $data[] = [
                'id' => $template->id,
                'name' => $template->name
            ];
        }

        return [
            'data' => $data
        ];
    }

    public static function getTemplateDetail($id)
    {
        $template = ContractTemplate::where('id', $id)->first();

        if (!$template) {
            return [];
        }

        return [
            'data' => [
                'id' => $template->id,
                'name' => $template->name,
                'desc' => $template->desc,
                'created_at' => local_date($template->created_at, "Y-m-d H:i:s")
            ]
        ];
    }

    public static function saveTemplate($data)
    {
        $template = new ContractTemplate();
        if (array_key_exists('id', $data) && $data['id']) {
            $template = ContractTemplate::where('id', $data['id'])->first();
        } else {
            $template->created_at = date('Y-m-d H:i:s', time());
        }
        foreach ($data as $key => $value) {
            $template->$key = $value;
        }
        $template->updated_at = date('Y-m-d H:i:s', time());
        $template->save();
    }

    public static function deleteTemplate($id)
    {
        $template = ContractTemplate::where('id', $id)->first();
        $template->status = 0;
        $template->updated_at = date('Y-m-d H:i:s', time());
        $template->save();
    }

    public static function getContractTemplate($contractId)
    {
        $contract = Contract::where('id', $contractId)->first();
        $template = ContractTemplate::where('id', $contract->template_id)->first();
        if (!$template) return [];

        return [
            'data' => [
                'id' => $template->id,
                'name' => $template->name,
                'desc' => $template->desc,
                'created_at' => local_date($template->created_at, 'Y-m-d H:i:s')
            ]
        ];
    }

    public static function changeContractProcess($data)
    {
        $contract = Contract::where('id', $data['id'])->first();
        $contract->process = $data['process'];
        if (!array_key_exists('process', $data)) {
            $data['process'] = '';
        }
        if ($contract->process == 1) {
            $contract->attachment = $data['attachment'];
        }
        if ($contract->process == 3) {
            $contract->pay_order = $data['pay_order'];
            if ($contract->pay_order != '') {
                $contract->order_at = date('Y-m-d H:i:s', time());
            }
        }
        if ($contract->process == 4) {
            $attachment = json_decode($contract->attachment, true);
            $attachment = array_merge($attachment, json_decode($data['attachment'], true));
            $contract->attachment = json_encode($attachment);
            if ($contract->pay_order == '') {
                $contract->order_at = date('Y-m-d H:i:s', time());
            }
        }
        $contract->process = $contract->process >= 4 ? 4 : $contract->process;
        $contract->updated_at = date('Y-m-d H:i:s', time());
        $contract->save();
    }

    public static function getUserLastContract($userId)
    {
        $contract = Contract::where('status', 1)->where('user_id', $userId)->orderBy('id', 'desc')->limit(1)->first();
        if (!$contract) return [];

        $template = ContractTemplate::where('id', $contract->template_id)->first();

        return [
            'data' => [
                'id' => $contract->id,
                'name' => $template->name,
                'desc' => $template->desc,
                'created_at' => local_date($template->created_at, 'Y-m-d H:i:s')
            ]
        ];
    }
}